package com.gp.tms.handler;


import com.gp.tms.utils.RespBean;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

/**
 * @description: 全局异常处理
 * @author: mavenue
 * @create: 2023-01-11 18:58
 **/

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public RespBean handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder sb = new StringBuilder("请求参数校验失败：");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            sb.append(fieldError.getField()).append("：").append(fieldError.getDefaultMessage()).append("；");
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return RespBean.error(sb.toString());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public RespBean handleConstraintViolationException(ConstraintViolationException e) {
        StringBuilder sb = new StringBuilder("请求参数校验失败：");
        for (ConstraintViolation<?> violation : e.getConstraintViolations()) {
            sb.append(violation.getMessage()).append("；");
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return RespBean.error(sb.toString());
    }

    @ExceptionHandler({AccessDeniedException.class})
    public RespBean handleAccessDeniedException(AccessDeniedException ex) {
        RespBean bean = RespBean.error("权限不足，请联系管理员");
        bean.setCode(403);
        return bean;
    }


//    @ExceptionHandler({Exception.class})
//    public RespBean handleException(Exception ex) {
//        return RespBean.error("系统未知错误，接口调用失败");
//    }

}
